package me.minecraft.mod.cobblemonbukkitevent.mixin;

import com.cobblemon.mod.common.Cobblemon;
import com.cobblemon.mod.common.api.battles.model.PokemonBattle;
import me.minecraft.mod.cobblemonbukkitevent.bukkit.EventFactory;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

import java.lang.reflect.Field;

/**
 * @author langle__
 * @version 1.0
 */
@Mixin(value = PokemonBattle.class, remap = false)
public class PokemonBattleMixin {

    @Unique
    private int lastTurn = -1;

    @Inject(method = {"turn"}, at = {@At("TAIL")}, remap = false)
    private void onTurn(int newTurnNumber, CallbackInfo ci) {
        try {
            PokemonBattle battle = (PokemonBattle) (Object) this;
            Field startedField = PokemonBattle.class.getDeclaredField("started");
            startedField.setAccessible(true);
            boolean started = startedField.getBoolean(battle);
            Field endedField = PokemonBattle.class.getDeclaredField("ended");
            endedField.setAccessible(true);
            boolean ended = endedField.getBoolean(battle);
            if (started && !ended && newTurnNumber != this.lastTurn) {
                this.lastTurn = newTurnNumber;
                EventFactory.callBattleTurnUpdateEvent(battle, newTurnNumber);
            }
        } catch (Exception e) {
            Cobblemon.LOGGER.error("Error in battle turn update: ", e);
        }
    }
}
